package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.NodeCandidateService;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.TaskCreatedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.FlowUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.ModelNextNodeCandidateSettings;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowNextNodeCandidateRepository;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.runtime.Execution;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntityManager;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.flowable.task.service.impl.util.CommandContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author liyang
 * @version 1.0
 * @date 2021-07-15 20:31:17
 **/
@Service
@Order(1)
public class SetTaskAssigneeProcessor implements TaskCreatedPostProcessor{

    @Autowired
    private TaskService taskService;

    @Autowired
    private FlowNextNodeCandidateRepository flowNextNodeCandidateRepository;

    @Autowired
    private NodeCandidateService nodeCandidateService;

    public void process(TaskEntity taskEntity) {
        Boolean isMultiTask = FlowUtils.getInstance().isMultiTaskActivity(taskEntity.getProcessInstanceId(),taskEntity.getTaskDefinitionKey());
        if (!isMultiTask){
            String parentExecutionId = null;

            String currentExecutionId = taskEntity.getExecutionId();
            //如果不为空，则是首次创建的任务
            //如果为空，则为加签或者委派后的任务
            if (StringUtils.isNotBlank(currentExecutionId)){
                ExecutionEntity executionEntity = nodeCandidateService.getSubProcessInstanceExecution(currentExecutionId);
                if (Objects.nonNull(executionEntity)){
                    parentExecutionId = executionEntity.getId();
                }else{
                    parentExecutionId = taskEntity.getProcessInstanceId();
                }
            }

            if (StringUtils.isNotBlank(parentExecutionId)){
                List<ModelNextNodeCandidateSettings> candidateSettingsList = flowNextNodeCandidateRepository.selectByProcessInstanceIdAndNodeCodeAndParentExecutionId(taskEntity.getProcessInstanceId(), taskEntity.getTaskDefinitionKey(),parentExecutionId);
                if (CollectionUtils.isNotEmpty(candidateSettingsList)) {
                    if (!taskEntity.getTaskDefinitionKey().equalsIgnoreCase(candidateSettingsList.get(0).getFromNodeCode())) {
                        List<IdentityLink> identityLinkList = taskService.getIdentityLinksForTask(taskEntity.getId());
                        if (CollectionUtils.isNotEmpty(identityLinkList)){
                            IdentityLinkEntityManager identityLinkEntityManager = CommandContextUtil.getIdentityLinkEntityManager();
                            identityLinkEntityManager.deleteIdentityLinksByTaskId(taskEntity.getId());
                        }
                    }

                    for (ModelNextNodeCandidateSettings candidate : candidateSettingsList) {
                        if ("STA".equalsIgnoreCase(candidate.getDataType())) {
                            taskService.addUserIdentityLink(taskEntity.getId(),candidate.getCode(),candidate.getDataType());
                        } else {
                            taskService.addGroupIdentityLink(taskEntity.getId(),candidate.getCode(),candidate.getDataType());
                        }
                    }
                }
            }
        }
    }


}
